﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using InfoJetSoft.Service.Entity;

//CID 0913 //2011.05.25 //Begin
namespace InfoJetSoft.Service.Util
{
    class InlineFileUtil
    {
        //CID 0618 //2010.07.05 //Begin
        //CID 0913 //2011.05.25 //Form
        public static bool isInlineFileEnabled(Form form)
        {
            if (ConfigUtil.InlineFilePath() == null && form.JetContext.InlineFileStorage == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        //CID 0618 //2010.07.05 //End

        public static string RestoreFile(Form form, string nodeValue)
        {
            //CID 0144 //2008.10.18 //Begin			
            if (form.JetContext.InlineFileStorage != null)
            {
                //CID 0374 //2009.07.29 //Begin
                if (InlineFileStorageUtil.NeedsRestore(form))
                {
                    byte[] fileContent = form.JetContext.InlineFileStorage.Restore(nodeValue);
                    //CID 0148 //2008.11.12 //Begin
                    string encodedValue = XFileAttachmentEncoder.encodeBASE64(form.JetContext.InlineFileStorage.GetName(nodeValue), fileContent);
                    return encodedValue;
                    //CID 0148 //2008.11.12 //End
                }
                //CID 0374 //2009.07.29 //End
            }
            //CID 0144 //2008.10.18 //End
            else
            {
                string path = form.HttpContext.Request.MapPath(nodeValue);
                //CID 0763 //2011.01.18 //Begin
                string folder = form.HttpContext.Request.MapPath(ConfigUtil.InlineFilePath()).ToLower() + "\\";
                if (!path.ToLower().StartsWith(folder))
                {
                    throw new InfoJetException("Denied to read " + nodeValue, "XFAESecurity");
                }
                //CID 0763 //2011.01.18 //End
                FileStream input = File.OpenRead(path);
                byte[] fileContent = new byte[input.Length];
                input.Read(fileContent, 0, fileContent.Length);
                input.Close();

                string encodedValue = XFileAttachmentEncoder.encodeBASE64(Path.GetFileName(path), fileContent);
                return encodedValue;
            }
            //CID 0913 //2011.05.25 //Begin
            return nodeValue;
            //CID 0913 //2011.05.25 //End
        }

        public static string RestoreImage(Form form, string nodeValue)
        {
            //CID 0144 //2008.10.18 //Begin			
            if (form.JetContext.InlineFileStorage != null)
            {
                //CID 0374 //2009.07.29 //Begin
                if (InlineFileStorageUtil.NeedsRestore(form))
                {
                    byte[] fileContent = form.JetContext.InlineFileStorage.Restore(nodeValue);
                    string encodedValue = XImageEncoder.encodeBASE64(fileContent);
                    return encodedValue;
                }
                //CID 0374 //2009.07.29 //End
            }
            //CID 0144 //2008.10.18 //End
            else
            {
                string path = form.HttpContext.Request.MapPath(nodeValue);
                //CID 0763 //2011.01.18 //Begin
                string folder = form.HttpContext.Request.MapPath(ConfigUtil.InlineFilePath()).ToLower() + "\\";
                if (!path.ToLower().StartsWith(folder))
                {
                    throw new InfoJetException("Denied to read " + nodeValue, "XIESecurity");
                }
                //CID 0763 //2011.01.18 //End
                FileStream input = File.OpenRead(path);
                byte[] fileContent = new byte[input.Length];
                input.Read(fileContent, 0, fileContent.Length);
                input.Close();

                string encodedValue = XImageEncoder.encodeBASE64(fileContent);
                return encodedValue;
            }
            //CID 0913 //2011.05.25 //Begin
            return nodeValue;
            //CID 0913 //2011.05.25 //End
        }

        //CID 0913 //2011.05.25 //Begin
        public static string CacheFile(Form form, string fileName, byte[] fileContent)
        {
            //CID 0144 //2008.10.18 //Begin
            if (form.JetContext.InlineFileStorage != null)
            {
                string fileUrl = form.JetContext.InlineFileStorage.Cache(fileName, fileContent);
                return fileUrl;
            }
            //CID 0144 //2008.10.18 //End
            else
            {
                //确定已定义InlineFilePath。
                //CID 0004 //2008.05.31 //Begin
                string inlineFilePath = InlineFileUtil.getFormInlineFileDiskPath(form); //CID 0033 //2008.06.25 //Method.
                //CID 0004 //2008.05.31 //End
                if (inlineFilePath != null)
                {
                    //生成一个唯一名称的目录。因为附件名可能相同，所以为了让附件以原名存储在服务器上，创建一个唯一名称目录来存放。
                    string directoryName = Guid.NewGuid().ToString();
                    string cachePath = form.HttpContext.Request.MapPath(inlineFilePath) + Path.DirectorySeparatorChar;
                    cachePath = cachePath + directoryName;
                    Directory.CreateDirectory(cachePath);

                    //写入磁盘。
                    cachePath = cachePath + Path.DirectorySeparatorChar + fileName;
                    FileStream output = File.Create(cachePath);
                    BinaryWriter writer = new BinaryWriter(output);
                    writer.Write(fileContent);

                    writer.Close();
                    output.Close();

                    //生成附件文件在服务器上的路径，供页面使用。
                    return inlineFilePath + "/" + directoryName + "/" + fileName;
                }
            }
            //CID 0913 //2011.05.25 //Begin
            return fileName;
            //CID 0913 //2011.05.25 //End
        }
        //CID 0913 //2011.05.25 //End

        //CID 0913 //2011.05.25 //Begin
        public static string CacheImage(Form form, string fileName, byte[] imageContent)
        {
            //CID 0144 //2008.10.18 //Begin
            if (form.JetContext.InlineFileStorage != null)
            {
                string fileUrl = form.JetContext.InlineFileStorage.Cache(fileName, imageContent);
                return fileUrl;
            }
            //CID 0144 //2008.10.18 //End
            else
            {
                //CID 0004 //2008.05.31 //Begin
                string inlineFilePath = InlineFileUtil.getFormInlineFileDiskPath(form); //CID 0033 //2008.06.25 //Method.
                //CID 0004 //2008.05.31 //End
                if (inlineFilePath != null)
                {
                    string directoryName = Guid.NewGuid().ToString();
                    string cachePath = form.HttpContext.Request.MapPath(inlineFilePath) + Path.DirectorySeparatorChar;
                    cachePath = cachePath + directoryName;
                    Directory.CreateDirectory(cachePath);

                    cachePath = cachePath + Path.DirectorySeparatorChar + fileName;
                    FileStream output = File.Create(cachePath);
                    //CID 0499 //2010.03.20 //Begin
                    output.Write(imageContent, 0, imageContent.Length);
                    //CID 0499 //2010.03.20 //End
                    output.Close();

                    return inlineFilePath + "/" + directoryName + "/" + fileName;
                }
            }
            //CID 0913 //2011.05.25 //Begin
            return fileName;
            //CID 0913 //2011.05.25 //End
        }
        //CID 0913 //2011.05.25 //End

        //CID 0033 //2008.06.25 //Begin
        public static string getFormInlineFileDiskPath(Form form)
        {
            string inlineFilePath = ConfigUtil.InlineFilePath();
            if (inlineFilePath == null)
            {
                return null;
            }
            else
            {
                if (form.HttpContext.Session == null)
                {
                    return inlineFilePath;
                }
                else
                {
                    string sessionId = form.HttpContext.Session.SessionID;
                    return inlineFilePath + System.IO.Path.DirectorySeparatorChar + InlineFileUtil.getMD5Hash(sessionId) + System.IO.Path.DirectorySeparatorChar + form.Id;
                }
            }
        }
        //CID 0033 //2008.06.25 //End

        //CID 0004 //2008.06.01 //Begin
        private static string getMD5Hash(string input)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string output = s.ToString();
            return output;
        }
        //CID 0004 //2008.06.01 //End
    }
}
//CID 0913 //2011.05.25 //End
